package net.wicp.tams.common.os.pool;

import org.apache.commons.pool2.impl.AbandonedConfig;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

import net.wicp.tams.common.Conf;

public class SSHPool extends GenericObjectPool<SSHConnection> {

	public SSHPool(String hostname, int port, String username, String password,
			GenericObjectPoolConfig<SSHConnection> poolConfig) {
		super(new SSHFactory(hostname, port, username, password), poolConfig);
		if (Conf.getBoolean("common.os.ssh.uncork.needcheck")) {
			AbandonedConfig abandonedConfig = new AbandonedConfig();
			abandonedConfig.setRemoveAbandonedOnMaintenance(true); // 在Maintenance的时候检查是否有泄漏
			abandonedConfig.setRemoveAbandonedOnBorrow(true); // borrow 的时候检查泄漏
			abandonedConfig.setRemoveAbandonedTimeout(Conf.getInt("common.os.ssh.uncork.removeAbandonedTimeout")); // 如果一个对象borrow之后10秒还没有返还给pool，认为是泄漏的对象
			super.setAbandonedConfig(abandonedConfig);
			// 维护任务执行的时间间隔:1000 * 60 * 3
			super.setTimeBetweenEvictionRunsMillis(Conf.getInt("common.os.ssh.uncork.timeBetweenEvictionRunsMillis"));
		}
	}

	public SSHPool(String hostname, int port, String username, String password) {
		this(hostname, port, username, password, new GenericObjectPoolConfig<SSHConnection>());
	}

	// 统一的用户名、密码、端口
	public SSHPool(String hostname) {
		this(hostname, new GenericObjectPoolConfig<SSHConnection>());
	}

	public SSHPool(String hostname, GenericObjectPoolConfig<SSHConnection> poolConfig) {
		this(hostname, Conf.getInt("common.os.ssh.port"), Conf.get("common.os.ssh.username"),
				Conf.get("common.os.ssh.pwd"), poolConfig);
	}

}
